package com.xja.web.domain.commons;

import com.xja.web.domain.model.WxUser;
import org.json.JSONObject;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public  class  Constant {
    //测试号appID
    public static final String appID="wxc30fe3abdea5d409";
    public static final String appsecret="cea2eee2711d1dc95b044085d3d3081d";
    //正式号appID
    public static final String APPID="wxc37f01894579f97b";
    public static final String APPSECRET="5ac97430e085abe7841209da8c29fca4";

    //全局唯一接口调用凭据
    public static String access_token="";
    public static Long access_token_time=1l;
    //微信JS接口的临时凭证
    public static String Jsapi_Ticket="";
    public static Long Jsapi_Ticket_time=1l;

    /**
     * access_token是公众号的全局唯一接口调用凭据
     * @return
     */
    public static String getAccessToken() {
        String str="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appID+"&secret="+appsecret;
        long nowtime = System.currentTimeMillis()/1000;
        JSONObject jsonObject=null;
        if (nowtime-access_token_time>7000){
            try {
                jsonObject  = HttpClienUtil.doGet(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (jsonObject.has("access_token")){
                access_token = jsonObject.get("access_token").toString();
                access_token_time = System.currentTimeMillis()/1000;
                return access_token;
            }
        }
        return access_token;
    }

    /**
     * 获取调用微信JS接口的临时票据
     *
     * @return
     */
    public static String getJsapi_Ticket() {
        String str="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getAccessToken()+"&type=jsapi";
        long nowtime = System.currentTimeMillis()/1000;
        JSONObject jsonObject=null;
        if (nowtime-Jsapi_Ticket_time>7000){
            try {
                jsonObject  = HttpClienUtil.doGet(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (jsonObject.has("ticket")){
                Jsapi_Ticket = jsonObject.get("ticket").toString();
                Jsapi_Ticket_time = System.currentTimeMillis()/1000;
                return Jsapi_Ticket;
            }
        }
        return Jsapi_Ticket;
    }

    /**
     * 获取config下timestamp: , // 必填，生成签名的时间戳
     *   nonceStr: '', // 必填，生成签名的随机串
     *   signature: '',// 必填，签名
     *   以及url
     * @return
     */
    public static Map<String,Object> getconfig(String url){
            //生成时间戳
           long timestamp = System.currentTimeMillis()/1000;
           //生成随机串
           String nonceStr = getNonceStr();
           //生成签名
           String s= "jsapi_ticket="+getJsapi_Ticket()+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;
           String signature = SHA1.encode(s);
           Map<String, Object> confing = new HashMap<>();
           confing.put("timestamp",timestamp);
           confing.put("nonceStr",nonceStr);
           confing.put("signature",signature);
           confing.put("appId",appID);
           return  confing;
    }
    public static String getNonceStr(){
        return UUID.randomUUID().toString().replaceAll("-","").substring(0,16);
    }
    /**
     * 根据全局唯一接口调用凭据和用户的openid获取用户信息
     * @param openId
     * @return
     * @throws IOException
     */
    public static  synchronized WxUser userInfo(String openId) throws IOException {
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+getAccessToken()+"&openid="+openId+"&lang=zh_CN";
        JSONObject jsonObject = HttpClienUtil.doGet(url);
        //Object subscribe_time = jsonObject.get("subscribe_time");
       // long time = Long.parseLong(subscribe_time.toString());
        //  System.out.println(subscribe_time);
       // Date date1 = new Date(time*1000);
        WxUser wxUser = JsonUtils.jsonToPojo(jsonObject.toString(), WxUser.class);
        //wxUser.setSubscribetime(date1);
        return wxUser;
    }

    /**
     * 获取网页授权access_token
     * @param code
     * @return
     * @throws IOException
     */
    public static  synchronized JSONObject getoAuthByCode(String code) throws IOException {
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
        JSONObject jsonObject = HttpClienUtil.doGet(url);
        return jsonObject;
    }

    /**
     * 微信登录授权获取用户信息
     * @param code
     * @return
     * @throws IOException
     */
    public static WxUser getUserInfoByOP(String code) {
        JSONObject jsonObject = null;
        WxUser wxUser =null;
        try {
            jsonObject = getoAuthByCode(code);
            if (jsonObject!=null&&jsonObject.has("access_token")){
                if (jsonObject.get("scope").equals("snsapi_userinfo")){
                    String urll="https://api.weixin.qq.com/sns/userinfo?access_token="+jsonObject.get("access_token").toString()+"&openid="+jsonObject.get("openid").toString()+"&lang=zh_CN";
                    JSONObject jsonObject1 = HttpClienUtil.doGet(urll);
                    wxUser = JsonUtils.jsonToPojo(jsonObject1.toString(), WxUser.class);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  wxUser;
    }

    public static JSONObject getQrCode(String scene_id){
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+getAccessToken();
        JSONObject jsonObject=null;
        try {
            String data="{\"expire_seconds\": 2592000, \"action_name\": \"QR_STR_SCENE\", " +
                    "\"action_info\": {\"scene\": {\"scene_str\": "+scene_id+"}}}";
             jsonObject = HttpClienUtil.doPost(url, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    /**
     * 微信授权
     * @param url
     * @return
     */
    public static String getUrl(String url){
        try {
            url= URLEncoder.encode(url,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String code="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constant.appID+"&redirect_uri="+url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        return  code;
    }
}
